package com.bootdo.clouddo.controller.juejin;

import java.util.Date;

import com.bootdo.clouddo.controller.common.CommonController;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.clouddo.domain.juejin.ArticleCollectionDO;
import com.bootdo.clouddo.domain.juejin.PostDO;
import com.bootdo.clouddo.service.juejin.IArticleCollectionService;
import com.bootdo.clouddo.service.juejin.IPostService;
import com.bootdo.clouddo.context.FilterContextHandler;
import com.bootdo.clouddo.utils.R;
import com.github.pagehelper.PageInfo;


@RestController
@RequestMapping("/article/collection")
public class ArticleCollectionController extends CommonController {

	
	@Autowired
	private IArticleCollectionService collectionService;
	
	@Autowired
	private IPostService postService;
	
	@GetMapping("/add/{id}")
	public R save(@PathVariable String id) {
		try {
			PostDO post = postService.get(id);
			if(post == null)
				return R.error("post_not_found");
			ArticleCollectionDO ac = new ArticleCollectionDO();
			ac.setUserId(Long.valueOf(getUid()));
			ac.setArticleId(id);
			ac.setCreateTime(new Date());
			ac.setTitle(post.getTitle());
			ac.setPublisherTime(post.getUpdatedAt());
			ac.setPublisherId(post.getUserId());
			ac.setSummaryInfo(post.getSummaryInfo());
			
			String userStr = post.getUser();
			if(StringUtils.isNotEmpty(userStr)) {
				try {
					JSONObject user = JSONObject.parseObject(userStr);
					ac.setPublisherName(user.getString("username"));
					ac.setPublisherAvatar(user.getString("avatarLarge"));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return R.data(collectionService.save(ac));
		}catch (Exception e) {
			e.printStackTrace();
		}
		return R.error();
	}

	@GetMapping("/list")
	public R findByUserId(@RequestParam(defaultValue="1")Integer page, @RequestParam(defaultValue="12")Integer size, String channel) {
		PageHelper.startPage(page, size);
		return R.data(new PageInfo<>(collectionService.findByUserId(getUid(), channel)));
	}

	
	@GetMapping("/del/{id}")
	public R deleteByUidAndAid(@PathVariable String id) {
		return R.data(collectionService.deleteByUidAndAid(getUid(), id));
	}
	
	
}
